﻿using IM.Easy.Core.Extensions;
using IM.Easy.Core.Services;
using IM.Easy.Entity.Log;
using IM.Easy.Entity.System;
using IM.Easy.Infrastructure.Query;
using IM.Easy.LogServices.Dtos;
using IM.Easy.LogServices.IServices;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.LogServices.Services
{
    /// <summary>
    /// 异常日志服务
    /// </summary>
    /// <param name="db"></param>
    public class ExceptionLogService(ISqlSugarClient db) : AppServices(db), IExceptionLogService
    {
        /// <summary>
        /// 写入异常日志
        /// </summary>
        public SysExceptionLog Insert(SysExceptionLog exceptionLog)
        {
            return Db.Insertable(exceptionLog).ExecuteReturnEntity();
        }

        /// <summary>
        /// 日志查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PageResponse<ExceptionLogDto> GetList(ExceptionLogQueryDto query)
        {
            var list = Db.Queryable<SysExceptionLog>();
            var exp = Expressionable.Create<SysExceptionLog>();
            exp = exp
                  .AndIF(query.BeginTime.HasValue, s => s.Time >= query.BeginTime)
                  .AndIF(query.EndTime.HasValue, s => s.Time <= query.EndTime)
                  .AndIF(!string.IsNullOrEmpty(query.Msg), s => s.Msg.Contains(query.Msg))
                  .AndIF(query.Type.HasValue, s => s.Type == query.Type)
;
            var page = list
                 .Includes(s => s.TraceInfo)
                 .Where(exp.ToExpression())
                 .ToPageListAsync<SysExceptionLog, ExceptionLogDto>(query);
            return page;
        }

        public bool Delete(params Guid[] id)
        {
            return Db.Deleteable<SysExceptionLog>(id).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 获取异常详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysExceptionLog GetById(Guid id)
        {
            var exceptionLog = Db.Queryable<SysExceptionLog>()
              .Includes(s => s.TraceInfo)
              .InSingle(id);
            return exceptionLog;
        }
    }
}
